<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="70"
          class="search-form"
        >
          <Form-item label="姓名" prop="name">
            <Input
              type="text"
              v-model="searchForm.name"
              placeholder="请输入姓名"
              :maxlength="10"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="接诊人" prop="expertName">
            <Input
              type="text"
              v-model="searchForm.expertName"
              placeholder="请输入接诊人"
              :maxlength="10"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="手机号" prop="phone">
            <Input
              type="text"
              v-model="searchForm.phone"
              placeholder="请输入手机号"
              :maxlength="11"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="场地名称" prop="siteName">
            <Input
              type="text"
              v-model="searchForm.siteName"
              placeholder="请输入场地名称"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="预约时间" prop="timeRange">
            <DatePicker
              type="daterange"
              v-model="searchForm.timeRange"
              format="yyyy-MM-dd"
              placeholder="选择预约时间"
              style="width: 200px"
            />
          </Form-item>
          <Button
            @click="handleSearch"
            class="search-btn"
            type="primary"
            icon="ios-search"
            >搜索</Button
          >
        </Form>
      </Row>
      <Table
        :loading="loading"
        border
        :columns="columns"
        class="mt_10"
        :data="data"
        ref="table"
      ></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page
          :current="searchForm.page"
          :total="total"
          :page-size="searchForm.rows"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10, 20, 50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>

    <!-- 查看模态框 -->
    <Modal v-model="detailFlag" title="详情" :width="800">
      <div class="modal-info" v-if="detailFlag">
        <p>基本信息</p>
        <div class="modal-row">
          <div>姓名：</div>
          <div>{{ detailRow.userVisitCard.username || "" }}</div>
        </div>
        <div class="modal-row">
          <div>手机号：</div>
          <div>{{ detailRow.userVisitCard.mobile || "" }}</div>
        </div>
        <div class="modal-row">
          <div>身份证：</div>
          <div>{{ detailRow.userVisitCard.idCard || "" }}</div>
        </div>
        <div class="modal-row">
          <div>性别：</div>
          <div>{{ detailRow.userVisitCard.sex == 1 ? "男" : "女" }}</div>
        </div>
        <div class="modal-row">
          <div>年龄：</div>
          <div>{{ myAge(detailRow.userVisitCard.birthday) }}</div>
        </div>
        <!-- <div class="modal-row">
          <div>身高：</div>
          <div>{{ detailRow.height || "--" }}cm</div>
        </div>
        <div class="modal-row">
          <div>体重：</div>
          <div>{{ detailRow.weight || "--" }}kg</div>
        </div>
        <div class="modal-row">
          <div>BMI：</div>
          <div>{{ detailRow.bmi || "--" }}kg/m²</div>
        </div> -->
        <div class="modal-row">
          <div>预约时段：</div>
          <div>{{ detailRow.appointmentTime || "" }}</div>
        </div>
        <div class="modal-row">
          <div>下单时间：</div>
          <div>{{ detailRow.createTime || "" }}</div>
        </div>
        <div class="modal-row">
          <div>接诊时间：</div>
          <div>{{ detailRow.receiveTime || "--" }}</div>
        </div>
        <p>运动健康处方</p>
        <!-- <div class="modal-row">
          <div>处方名称：</div>
          <div>{{ detailRow.expertPrescription.name || "" }}</div>
        </div>
        <div class="modal-row">
          <div>诊断结果：</div>
          <div>{{ detailRow.expertPrescription.diagnosticResults || "" }}</div>
        </div>
        <div class="modal-row">
          <div>专家建议：</div>
          <div>{{ detailRow.expertPrescription.expertAdvice || "" }}</div>
        </div> -->
        <div class="modal-column" v-if="detailRow.prescriptionName">
          <div class="recipel-box">
            <div class="recipel-name">{{ detailRow.prescriptionName }}</div>
            <a href="#" @click="recipelDetailModel = true">详情>></a>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button @click="detailFlag = false">关闭</Button>
      </div>
    </Modal>
    <Modal
      v-model="recipelDetailModel"
      :title="detailRow.prescriptionName"
      @on-cancel="cancel"
    >
      <div v-html="detailRow.expertAdvice"></div>
      <div v-if="filePath">
        <div v-for="(ie, k) in filePath" :key="k" class="cfList">
          <div>
            <Icon type="ios-folder" />
            <span style="margin-left: 5px">{{ ie.fileName }}</span>
          </div>
          <div>
            <a href="#" @click="preFile(ie.url)">预览</a>
            <a href="#" @click="downFile(ie.url, ie.fileName)">下载</a>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import * as API_Consult from "@/api/consult.js";
import { getFileInfo } from "@/api/community.js";
export default {
  name: "consult-appointment",
  data() {
    return {
      filePath: [],
      recipelDetailModel: false,
      loading: true, // 表单加载状态
      searchForm: {
        // 请求参数
        page: 1,
        rows: 10,
        name: null, //姓名
        expertName: null, //接诊人
        phone: null, //手机号
        siteName: null, //场地名称
        timeRange: [], // 下单时间范围
        start: null, //下单开始时间
        end: null, //下单结束时间
      },
      columns: [
        {
          title: "姓名",
          tooltip: true,
          minWidth: 120,
          render: (h, params) => {
            return h("span", {}, params.row.userVisitCard.username);
          },
        },
        {
          title: "身份证号",
          tooltip: true,
          minWidth: 180,
          render: (h, params) => {
            return h("span", {}, params.row.userVisitCard.idCard);
          },
        },
        {
          title: "手机号",
          tooltip: true,
          minWidth: 120,
          render: (h, params) => {
            return h("span", {}, params.row.userVisitCard.mobile);
          },
        },
        { title: "预约时段", key: "appointmentTime", minWidth: 180, tooltip: true },
        { title: "下单时间", key: "createTime", minWidth: 180, tooltip: true },
        { title: "接诊时间", key: "receiveTime", minWidth: 180, tooltip: true },
        {
          title: "接诊人",
          tooltip: true,
          minWidth: 120,
          render: (h, params) => {
            return h("span", {}, params.row.expert.realName);
          },
        },
        {
          title: "场地名称",
          tooltip: true,
          minWidth: 150,
          render: (h, params) => {
            return h("span", {}, params.row.site ? params.row.site.siteName : "");
          },
        },
        {
          title: "操作",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            return h(
              "div",
              {
                style: { display: "flex", justifyContent: "center" },
              },
              [
                h(
                  "Button",
                  {
                    props: { type: "error", size: "small", ghost: true },
                    on: {
                      click: () => {
                        this.handleView(params.row);
                      },
                    },
                  },
                  "详情"
                ),
              ]
            );
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
      detailFlag: false, // 详情弹窗
      detailRow: {}, //查看数据
    };
  },
  methods: {
    cancel() {
      this.optionsModal = {
        name: "",
        expertAdvice: "",
        filePath: [],
      };
    },
    //根据日期算年龄
    myAge(birthday) {
      if (birthday && birthday != "null" && birthday != "undefined") {
        birthday = birthday.split("-");
        let date = new Date();
        let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
        let age = today.map((val, index) => {
          return val - birthday[index];
        });
        if (age[2] < 0) {
          let lastMonth = new Date(today[0], today[1], 0);
          age[1]--;
          age[2] += lastMonth.getDate();
        }
        if (age[1] < 0) {
          age[0]--;
          age[1] += 12;
        }
        return age[0] + "岁";
      } else {
        return "--";
      }
    },
    myBrowser() {
      var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf("OPR") > -1;
      if (isOpera) {
        return "Opera";
      } // 判断是否Opera浏览器 OPR/43.0.2442.991
      // if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) { return 'IE' } // 判断是否IE浏览器
      if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
      } // 判断是否Firefox浏览器Firefox/51.0
      if (userAgent.indexOf("Trident") > -1) {
        return "IE";
      } // 判断是否IE浏览器  Trident/7.0; rv:11.0
      if (userAgent.indexOf("Edge") > -1) {
        return "Edge";
      } // 判断是否Edge浏览器  Edge/14.14393
      if (userAgent.indexOf("Chrome") > -1) {
        return "Chrome";
      } // Chrome/56.0.2924.87
      if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
      } // 判断是否Safari浏览器 AppleWebKit/534.57.2 Version/5.1.7 Safari/534.57.2
    },
    //处方文件预览
    preFile(url) {
      let officeUrl = "https://view.xdocin.com/view?src=" + url;
      window.open(officeUrl, "_target");
    },
    // 检查是否有下载权限
    checkAuthority() {
      return new Promise((resolve) => {
        API_Consult.postDownAuthority()
          .then((res) => {
            if (res.code == 200) {
              resolve(true);
            } else {
              resolve(false);
            }
          })
          .catch(() => {
            resolve(false);
          });
      });
    },
    //处方文件下载
    async downFile(url, tagFileName) {
      let check = await this.checkAuthority();
      if (!check) return;
      const imgType = ["png", "jpg", "jpeg", "gif"];
      let index = url.lastIndexOf(".");
      let ext = url.substr(index + 1);
      if (imgType.includes(ext)) {
        if (this.myBrowser() === "IE" || this.myBrowser() === "Edge") {
          this.saveAs(url, tagFileName);
          return;
        }
        var image = new Image();
        image.setAttribute("crossOrigin", "anonymous");
        var _this = this;
        image.onload = function () {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          var URL = canvas.toDataURL("image/png"); //得到图片的base64编码数据
          var a = document.createElement("a"); // 生成一个a元素
          var event = new MouseEvent("click"); // 创建一个单击事件
          a.download = tagFileName || "图片";
          a.href = URL; // 将生成的URL设置为a.href属性
          a.dispatchEvent(event); // 触发a的单击事件
        };
        image.src = url;
      } else {
        fetch(url)
          .then((res) => res.blob())
          .then((blob) => {
            const a = document.createElement("a");
            const objectUrl = window.URL.createObjectURL(blob);
            a.download = tagFileName;
            a.href = objectUrl;
            a.click();
            window.URL.revokeObjectURL(objectUrl);
            a.remove();
          });
      }
    },
    saveAs(fileUrl, tagFileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE11 发现在微软在ie10 和ie11中有两个特有的方法：window.navigator.msSaveBlob和window.navigator.msSaveOrOpenBlob 方法，
        this.getBlob(fileUrl).then((blob) => {
          window.navigator.msSaveBlob(blob, tagFileName);
        });
      }
    },
    /**
     * [getBlob 获取二进制流]
     * @param  {[String]}     url     [url]
     * @param  {[Blob]}               [文件二进制]
     */
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      });
    },
    // 分页 改变页码
    changePage(v) {
      this.searchForm.page = v;
      this.getData();
    },
    // 分页 改变页数
    changePageSize(v) {
      this.searchForm.rows = v;
      this.searchForm.page = 1;
      this.getData();
    },
    // 搜索
    handleSearch() {
      this.searchForm.page = 1;
      this.searchForm.rows = 10;
      this.getData();
    },
    // 详情
    handleView(v) {
      this.detailFlag = true;
      if (v.expertPrescription.file) {
        v.imgList = v.expertPrescription.file.split(",");
      }
      this.detailRow = v;
      if (this.detailRow.filePath) {
        getFileInfo(this.detailRow.id).then((res) => {
          if (res.success) {
            this.filePath = res.result;
          }
        });
      }
    },
    // 日期格式处理
    formatDate(date) {
      if (date) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let m = month >= 10 ? month : "0" + month;
        let d = day >= 10 ? day : "0" + day;
        return `${year}-${m}-${d}`;
      } else {
        return null;
      }
    },
    // 查询预约列表
    getData() {
      let params = Object.assign({}, this.searchForm);
      params.start = this.formatDate(params.timeRange[0]);
      params.end = this.formatDate(params.timeRange[1]);
      delete params.timeRange;

      this.loading = true;

      API_Consult.postRegisterPage(params)
        .then((res) => {
          if (res.success) {
            this.data = res.result.list;
            this.total = parseInt(res.result.total);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
  mounted() {
    this.getData();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .ivu-table-wrapper {
  width: 100%;
}
::v-deep .ivu-card {
  width: 100%;
}
.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.modal-info {
  height: 600px;
  overflow-y: auto;
  p::before {
    display: inline-block;
    content: "";
    width: 3px;
    height: 14px;
    vertical-align: top;
    border-radius: 2px;
    margin-right: 20px;
    background-color: #1989fa;
  }
  .modal-row {
    display: flex;
    line-height: 35px;
    padding: 0 20px;
    > div:first-child {
      width: 90px;
      color: #777777;
    }
    > div:last-child {
      flex: 1;
      word-break: break-all;
    }
    img {
      width: 120px;
      height: 120px;
      margin: 0 10px 10px 0;
    }
  }
  .modal-row2 {
    line-height: 35px;
    padding: 0 20px;
    > div:first-child {
      width: 160px;
      color: #777777;
    }
    > div:last-child {
      word-break: break-all;
    }
  }
  .divider {
    margin: 20px;
    border-bottom: 1px solid #e4e4e4;
  }
}
.recipel-box {
  display: flex;
  margin-top: 20px;
  margin-left: 10px;
}
.modal-column {
  padding: 0 20px;
}
.recipel-name {
  margin-right: 50px;
}
.cfList {
  display: flex;
  > div:first-child {
    margin-right: 32px;
  }
  > div {
    margin-top: 20px;
  }
  a {
    color: #ff5c58 !important;
    margin-right: 10px;
  }
}
</style>
